#include <iostream>
#include <string>
#include <mysql/mysql.h>

using namespace std;

const char* Host = "127.0.0.1";
const char* User = "laptop";
const char* Password = ""; //todo
const char* DataBase = "connection";
constexpr unsigned int Port = 18989;


int main() {
    // cout << mysql_get_client_info() << endl;
    MYSQL* my = mysql_init(nullptr); // 创建并初始化一个MySQL对象，并获取它的句柄。
    if (nullptr == my) {
        cerr << "mysql_init err!" << endl;
        exit(EXIT_FAILURE);
    }

    // 连接数据库
    if (nullptr == mysql_real_connect(my, Host, User, Password, DataBase, Port, nullptr, 0)) {
        cerr << "mysql_real_connect fail!" << endl;
        exit(EXIT_FAILURE);
    }
    cout << "connect mysql success!" << endl;
    
    if (0 != mysql_set_character_set(my, "utf8")) {
        cerr << "mysql_set_character_set err!" << endl;
        exit(EXIT_FAILURE);
    }

    string sql;
    for (;;) {
        cout << "MySQL>>> ";
        if (!getline(cin, sql) || sql == "quit") {
            cout << "bye bye" << endl;
            break;
        }
        int n = mysql_query(my, sql.c_str());
        if (0 == n) {
            cout << sql << " success " << endl;
        }
        else {
            cerr << sql << " failed " << n << endl;
            continue;
        }

        MYSQL_RES* result = mysql_store_result(my);
        if (nullptr == result) {
            cout << "mysql_store_result err! " << mysql_error(my) << endl;
            exit(EXIT_FAILURE);
        }

        auto rows = mysql_num_rows(result);
        auto fields = mysql_num_fields(result);

        {
            auto fields_array = mysql_fetch_fields(result);
            for (int i = 0; i < fields; ++i) {
                cout << fields_array[i].name << "\t";
            }
            cout << "\n";
        }

        for (int i = 0; i < rows; ++i) {
            auto row = mysql_fetch_row(result);
            for (int j = 0; j < fields; ++j) {
                cout << row[j] << "\t";
            }

            cout << "\n";
        }

        mysql_free_result(result);
    }

    mysql_close(my); // 关闭MySQL
    return 0;
}